#include <iostream>
#include <vector>
using namespace std;


struct list
{
    int data;
    list * next=nullptr;
};

int sum=0;

void build(list *&T)
{
    list *p=T;
    list *q;
    int n;
    cin>>n;
    for(int i=0;i<n;i++)
    {
        q=new list;
        cin>>q->data;
        p->next=q;
        p=q;
    }
}

void del(list *T,list *d)
{
    list *p=T;
    if(p==d)
    {
        T= nullptr;
        return;
    }
    while(nullptr!=p)
    {
        if(p->next==d)
        {
            break;
        }
        p=p->next;
    }
    p->next=d->next;
    delete d;
    return;
}

void find(list *&T)
{
    list *p=T->next;
    list *x=T->next;
    list *y=T->next->next;
    while(nullptr!=p)
    {
        if(x->data>p->data)
        {
            x=p;
        }
        p=p->next;
    }
    p=T->next;
    while(nullptr!=p)
    {
        if(y->data>p->data&&p!=x)
        {
            y=p;
        }
        p=p->next;
    }
    p=T;
    while(nullptr!=p->next)
    {
        p=p->next;
    }
    int sun=x->data+y->data;
    sum+=sun;
    del(T,x);
    del(T,y);
    list *q=new list;
    q->data=sun;
    p->next=q;
    p=q;
    if(T->next!=nullptr)
    {
        find(T);
    }
    else
    {
        cout<<sum;
    }
}




int main() {
    list *head=new list;
    head->data=0;
    build(head);
    find(head);
    return 0;
}
